<?php

class SJB_Admin_Builder_Save extends SJB_Function
{
	public function isAccessible()
	{
		$this->setPermissionLabel('edit_form_builder');
		return parent::isAccessible();
	}

	public function execute()
	{
		$builderLayoutID = SJB_Request::getVar('builder-layout', null, 'GET');
		$listingTypeID = SJB_Request::getVar('listing_type_id', null);
		$listingTypeSID = SJB_ListingTypeManager::getListingTypeSIDByID($listingTypeID);
		if ($builderLayoutID && $listingTypeID) { // saving layout here
			SJB_DisplayFormFieldsBuilder::setDisplayLayout($listingTypeID, $builderLayoutID);
		}
		elseif ($listingTypeSID) { // saving fields order here

			$fields = explode(',', SJB_Request::getVar('order', '', 'POST'));
			$fieldsHolderID = SJB_Request::getVar('fhid', null, 'POST');

			if (!empty($fields) && is_array($fields) && $fieldsHolderID) {

				$results = SJB_FieldsHolder::saveProcess($listingTypeSID, $fieldsHolderID, $fields);
				foreach ($results as $saved) {
					if (!$saved) {
						echo '-1';
						exit;
					}
				}
				echo '1';
				exit;
			}
			echo '0';
		}
		exit;
	}
}
